# 描述: Doris连接器，统一管理连接池，并提供统计的API获取数据库连接
# 作者: 王茂林
# 时间: 2025/5/26 9:21
import pymysql
from pymysqlpool import ConnectionPool

from common.configuration import get_doris_settings


class DorisConnectionManager:
    # 类变量，用于存储单例实例
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
            cls._instance._init_pool()
        return cls._instance

    def _init_pool(self):
        default_pool_kwargs = {
            'autocommit': True,
            'charset': 'utf8mb4',
            'cursorclass': pymysql.cursors.DictCursor
        }
        settings = get_doris_settings()
        self.pool = ConnectionPool(
            host=settings["host"],
            port=settings["port"],
            user=settings["user"],
            password=settings["password"],
            database=settings["database"],
            **default_pool_kwargs
        )

    @staticmethod
    def get_connection():
        """
        从连接池获取一个数据库连接
        :return: 数据库连接对象
        """
        conn_manager = DorisConnectionManager()
        return conn_manager.pool.get_connection()
